package com.visec.hdy.sync.ftp.code;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTPFile;

import com.visec.hdy.sync.ftp.code.FtpDataConvert.FtpTData;
import com.visec.hdy.sync.ftp.config.SyncFileMsg;
import com.visec.hdy.sync.ftp.config.SyncGetConfig;
import com.visec.hdy.transmission.ftp.FtpFactory;
import com.visec.hdy.transmission.ftp.code.FtpClientInter;
import com.visec.hdy.utils.TimeUtil;

public class FtpGetManager implements GetManager {

	private SyncGetConfig ftpGetConfig;
	private ThreadLocal<FtpClientInter> threadLocal;

	protected FtpGetManager() {

	}

	public static FtpGetManager getInstance(SyncGetConfig f) {
		FtpGetManager fgm = new FtpGetManager();
		fgm.ftpGetConfig = f;
		fgm.threadLocal = new ThreadLocal<FtpClientInter>();
		return fgm;
	}

	public SyncGetConfig getFtpGetConfig() {
		return ftpGetConfig;
	}

	public void setFtpGetConfig(SyncGetConfig ftpGetConfig) {
		this.ftpGetConfig = ftpGetConfig;
	}

	public FtpGetManager copy() {
		FtpGetManager fgm = new FtpGetManager();
		fgm.setFtpGetConfig(ftpGetConfig);
		return fgm;
	}

	private synchronized FtpClientInter getFtpClientInter() {
		if (threadLocal.get() != null) {
			FtpClientInter ftpClientInter = threadLocal.get();
			ftpClientInter.login();
			return ftpClientInter;
		}
		FtpClientInter createClient = FtpFactory.getInstance().createClient(ftpGetConfig.getFtpModel());
		createClient.login();
		threadLocal.set(createClient);
		return createClient;
	}

	@Override
	public String checkFile(SyncFileMsg ftpFileMsg) {

		FtpClientInter fci = getFtpClientInter();

		if (!entryDir(ftpFileMsg, fci)) {
			return "false";
		}

		FTPFile file = fci.getFile(ftpFileMsg.getFtpFileModel().getFileName());
		if (file == null) {
			return "false";
		}

		if (file.getSize() == ftpFileMsg.getFtpFileModel().getFileSize()) {
			return "true";
		} else {
			return "false";
		}

		// FtpFileManager ftpFileManager = ftpGetConfig.getFtpFileManager();
		// FtpClientInter fci = getFtpClientInter();
		//
		// if (!entryDir(ftpFileMsg, fci)) {
		// return "false";
		// }
		//
		// FTPFile file =
		// fci.getFile(ftpFileMsg.getFtpFileModel().getFileName());
		//
		// if (file == null) {
		// ftpFileManager.isLater(ftpFileMsg);
		// return "false";
		// }
		//
		// ftpFileMsg.getFtpFileModel().setFileSize(file.getSize());
		// ftpFileMsg.getFtpFileModel().setModifyTime(TimeUtil.fomatDate(file.getTimestamp()));
		//
		// if (ftpFileManager.isLater(ftpFileMsg)) {
		// return "true";
		// } else {
		// return "false";
		// }
	}

	// static Logger l = Logger.getLogger(FtpGetManager.class);

	@Override
	public String syncFile(SyncFileMsg ftpFileMsg, InputStream i) {
		// FtpFileManager ftpFileManager = ftpGetConfig.getFtpFileManager();

		FtpClientInter fci = getFtpClientInter();
		if (entryDir(ftpFileMsg, fci)) {
			if (fci.setFileType(ftpFileMsg.getFtpFileModel().getType())) {
				OutputStream uploadFile = fci.uploadFile(ftpFileMsg.getFtpFileModel().getFileName(), false);
				byte[] b = new byte[ftpGetConfig.getDefalutSize()];
				int a = 0;
				try {
					long start = System.currentTimeMillis();
					FtpDataConvert fdc = new FtpDataConvert();
					while ((a = i.read(b)) > 0) {
						if (fdc.put(b, a)) {
							FtpTData ftpTData = fdc.get();
							if (ftpTData != null) {
								uploadFile.write(ftpTData.getB(), 0, ftpTData.getI());
							}
							break;
						}
						FtpTData ftpTData = fdc.get();
						if (ftpTData != null) {
							uploadFile.write(ftpTData.getB(), 0, ftpTData.getI());
						}
					}
					uploadFile.close();
					fci.completePendingCommand();

					long end = System.currentTimeMillis();
					try {
						Runtime.getRuntime()
								.exec("logger -p local5.info ftp-server-get-file=ftpId:" + ftpFileMsg.getFtpId() + ",file dir:"
										+ ftpFileMsg.getFtpFileModel().getDir() + ",file name:"
										+ ftpFileMsg.getFtpFileModel().getFileName() + ",file size:" + fdc.getAll()
										+ ",start time:" + start + ",end time:" + end);
					} catch (Exception e) {
						// TODO: handle exception
						
					}
					if (fdc.getAll() != ftpFileMsg.getFtpFileModel().getFileSize()) {
						return "false";
					}

				} catch (IOException e) {
					// TODO Auto-generated catch block
					// e.printStackTrace();
					return "false";
				}
				return "true";
			} else {
				return "false";
			}
		} else {
			return "false";
		}
	}

	@Override
	public String deleteFile(SyncFileMsg ftpFileMsg) {

		FtpClientInter fci = getFtpClientInter();

		if (entryDir(ftpFileMsg, fci)) {
			if (fci.deleteFile(ftpFileMsg.getFtpFileModel().getFileName())) {
				return "true";
			} else {
				return "false";
			}
		} else {
			return "false";
		}
	}

	@Override
	public String clearFile(SyncFileMsg ftpFileMsg) {
		System.out.println("clear");
		return "sb";
	}

	@Override
	public void close() throws IOException {
		// TODO Auto-generated method stub
		if (this.threadLocal.get() != null) {
			this.threadLocal.get().logout();
			this.threadLocal.remove();
		}
	}

	protected boolean entryDir(SyncFileMsg ftpFileMsg, FtpClientInter fci) {
		String folder = ftpFileMsg.getFtpFileModel().getDir();
		if (!ftpFileMsg.getFtpFileModel().getDir().startsWith("/")) {
			folder = "/" + folder;
		}
		boolean entryDir = fci.entryDir(folder);
		if (!entryDir) {
			fci.createDir(folder);
			return fci.entryDir(folder);
		}
		return entryDir;
	}

	public void resetData() {
		ftpGetConfig.getFtpFileManager().reset();
	}

	@Override
	public String checkAndSync(SyncFileMsg ftpFileMsg) {
		// TODO Auto-generated method stub
		FtpFileManager ftpFileManager = ftpGetConfig.getFtpFileManager();
		FtpClientInter fci = getFtpClientInter();

		if (!entryDir(ftpFileMsg, fci)) {
			return "false";
		}

		FTPFile file = fci.getFile(ftpFileMsg.getFtpFileModel().getFileName());

		if (file == null)
			return "false";

		ftpFileMsg.getFtpFileModel().setFileSize(file.getSize());
		ftpFileMsg.getFtpFileModel().setModifyTime(TimeUtil.fomatDate(file.getTimestamp()));

		if (ftpFileManager.isLater(ftpFileMsg)) {
			return "true";
		} else {
			return "false";
		}
	}

}
